package com.tf_cut.backend.platform.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.collect.Lists;
import com.tf_cut.backend.common.pojo.PageInfo;
import com.tf_cut.backend.common.pojo.Result;
import com.tf_cut.backend.platform.pojo.PersonalTax;
import com.tf_cut.backend.platform.service.GrantDetailService;
import com.tf_cut.backend.platform.service.GrantService;
import com.tf_cut.backend.platform.service.PersonalTaxService;
import com.tf_cut.backend.platform.service.SetHistoryService;
import com.tf_cut.backend.platform.vo.GrantDetailVo;
import com.tf_cut.backend.platform.vo.OrderDetailVO;
import com.tf_cut.backend.platform.vo.PersonalTaxVo;
import com.tf_cut.backend.platform.vo.SetHistoryVo;
import com.tf_cut.backend.seller.service.SellerOrderService;
import com.tf_cut.backend.seller.vo.SellerOrderVo;
import com.tf_cut.backend.service.service.ServicePersonalIncomeTaxSetingService;
import com.tf_cut.backend.service.vo.ServicePersonalIncomeTaxSetingVo;
import com.tf_cut.backend.util.CalendarUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

@Slf4j
@RestController
@RequestMapping("/backend/admin/platform/grant")
public class GrantController {
    @Autowired
    private GrantService grantService;
    @Autowired
    private GrantDetailService grantDetailService;
    @Autowired
    private SellerOrderService sellerOrderService;
    
    @Autowired
    private PersonalTaxService personalTaxService;
    
    @Autowired
    private ServicePersonalIncomeTaxSetingService servicePersonalIncomeTaxSetingService;
    
    @Autowired
    private SetHistoryService setHistoryService;


    @PostMapping("/list")
    public String queryPlatformGrantList(String json) {
        Result<List<SellerOrderVo>> result;
        try {
            SellerOrderVo avo = JSON.parseObject(json, SellerOrderVo.class);
            PageInfo<SellerOrderVo> listSellerOrder =sellerOrderService.findListSellerOrder(avo);
            return JSON.toJSONString(listSellerOrder,SerializerFeature.WriteDateUseDateFormat);
        } catch (Exception e) {
            log.error("queryPlatformGrantList error:{}", e.getMessage(), e);
            result = Result.of(Lists.newArrayList());
            result.setMsg(e.getMessage());
            result.setFlag(false);
        }
        return JSON.toJSONString(result, SerializerFeature.WriteDateUseDateFormat);
    }

    @PostMapping("/listInfo")
    public String queryPlatformGrantListInfo(String platformGrantId) {
        Result<List<GrantDetailVo>> result;
        try {
            GrantDetailVo svo = GrantDetailVo.builder().orderId(platformGrantId).build();
            List<GrantDetailVo> grantVoList = grantDetailService.queryGrantDetailList(svo);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("code","0");
            map.put("msg","");
            map.put("count","10000");
            map.put("data",grantVoList);
            return JSON.toJSONString(map, SerializerFeature.WriteDateUseDateFormat);
        } catch (Exception e) {
            log.error("queryPlatformGrantListInfo error:{}", e.getMessage(), e);
            result = Result.of(Lists.newArrayList());
            result.setMsg(e.getMessage());
            result.setFlag(false);
            return JSON.toJSONString(result, SerializerFeature.WriteDateUseDateFormat);
        }
    }

    @GetMapping("/export")
    public List<GrantDetailVo> queryPlatformGrantExportList(String platformGrantId) {
        List<GrantDetailVo> grantVoList = Lists.newArrayList();
        try {
            GrantDetailVo svo = GrantDetailVo.builder().orderId(platformGrantId).build();
            grantVoList = grantDetailService.queryGrantDetailList(svo);
            return grantVoList;
        } catch (Exception e) {
            log.error("queryPlatformGrantExportList error:{}", e.getMessage(), e);
        }
        return grantVoList;
    }
    
    @GetMapping(value = "/queryByName")
    public List<PersonalTaxVo> queryByName(@RequestParam("payeeName") String payeeName,
            @RequestParam("serviceName") String serviceName,
            @RequestParam("time") String[] time,@RequestParam("cardCode") String cardCode,
            @RequestParam("startaxAmount") String startaxAmount,@RequestParam("endtaxAmount") String endtaxAmount,
            @RequestParam("startaxMoney") String startaxMoney,@RequestParam("endtaxMoney") String endtaxMoney){
    	// 自定义
    	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
    	String startDate= "";
    	String endDate = "";
    	List<PersonalTaxVo> list = new ArrayList<>();
    	if(time.length == 0){
    		list.addAll(grantDetailService.queryByName(payeeName,serviceName,startDate,endDate,cardCode,startaxAmount,endtaxAmount,startaxMoney,endtaxMoney));
    	}else{
    		for(int i=0;i<time.length;i++){
    			startDate= time[i] + "-01 00:00:00";
        		String num = time[i].substring(0, 4);
                String strh = time[i].substring(5,7);
                endDate= df.format(CalendarUtil.getLastDayOfMonth(Integer.valueOf(num).intValue(),Integer.valueOf(strh).intValue()));
                list.addAll(grantDetailService.queryByName(payeeName,serviceName,startDate,endDate,cardCode,startaxAmount,endtaxAmount,startaxMoney,endtaxMoney));
    		}
    	}
        return list;
    }


    @GetMapping(value = "/queryByNames")
    public List<OrderDetailVO> queryByNames(@RequestParam("time") String time,@RequestParam("tax") String tax){
    		// 自定义
        	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
        	String startDate= "";
        	String endDate = "";
        	if(time.equals("") || time == null){
//        		endDate=CalendarUtil.getYearMonth();
//        		String num = endDate.substring(0, 4);
//                String strh = endDate.substring(5,7);
//                endDate= df.format(CalendarUtil.getLastDayOfMonth(Integer.valueOf(num).intValue(),Integer.valueOf(strh).intValue()));
//        		startDate=CalendarUtil.getYearMonth()+"-01 00:00:00";
        		List<OrderDetailVO> list = new ArrayList<>();
        		return list;
        	}else{
        		startDate= time + "-01 00:00:00";
        		String num = time.substring(0, 4);
                String strh = time.substring(5,7);
                endDate= df.format(CalendarUtil.getLastDayOfMonth(Integer.valueOf(num).intValue(),Integer.valueOf(strh).intValue()));
        	}
        return grantDetailService.queryByNames(startDate,endDate,tax);
    }
    
    
    @PostMapping(value = "/findByTime")
    public List<OrderDetailVO> findByTime(){
        return grantDetailService.findByTime();
    }
    
    @PostMapping(value = "/findByQueryTime")
    public List<PersonalTaxVo> findByQueryTime(){
        return grantDetailService.findByQueryTime();
    }
    
    /**
     * 申请记录查询接口
     * 在admin包platform包下的GrantController类下的queryApply方法
     * @param page
     * @param rows
     * @param sellerName
     * @param serviceName
     * @param startDate
     * @param endDate
     * @param orderId
     * @return
     */
    @RequestMapping("/queryApply")
    public String queryApply(@RequestParam("page") int page,@RequestParam("rows") int rows,@RequestParam("sellerName") String sellerName,
    		@RequestParam("serviceName") String serviceName,@RequestParam("startDate") String startDate,
            @RequestParam("endDate") String endDate,
            @RequestParam("orderId") String orderId) {
    	PageInfo<SellerOrderVo> sellerBillAndConsigneeVoPageInfo = sellerOrderService.queryApply(page,rows,sellerName,serviceName,startDate,endDate,orderId);
    	return JSON.toJSONString(sellerBillAndConsigneeVoPageInfo, SerializerFeature.WriteDateUseDateFormat);
    	
    }
    
    
    @RequestMapping("/exportGrant")
    public List<SellerOrderVo> exportGrant(@RequestParam("sellerName") String sellerName,
    		@RequestParam("serviceName") String serviceName,@RequestParam("startDate") String startDate,
            @RequestParam("endDate") String endDate,
            @RequestParam("orderId") String orderId) {
    	return sellerOrderService.exportGrant(sellerName,serviceName,startDate,endDate,orderId);
    	
    }
    
    @RequestMapping("/save")
    public String save(@RequestParam("cardCode")String cardCode,@RequestParam("time")String time,@RequestParam("payAmount1")double payAmount1,@RequestParam("nottax")String nottax,
			@RequestParam("perAmount")String perAmount,@RequestParam("serviceId")String serviceId,@RequestParam("sellerId")String sellerId,@RequestParam("tax")double tax,
			@RequestParam("ffMoney")String ffMoney,@RequestParam("payeeName")String payeeName,@RequestParam("provideDetailId")String provideDetailId){
    		PersonalTaxVo PersonalTax = new PersonalTaxVo();
    		PersonalTax.setCardCode(cardCode);
    		PersonalTax.setCreateTime(time+"-01");
    		PersonalTax.setPayAmount(payAmount1);
    		PersonalTax.setTaxAmount(nottax);
    		PersonalTax.setTaxPercent(perAmount);
    		PersonalTax.setSellerId(sellerId);
    		PersonalTax.setServiceId(serviceId);
    		PersonalTax.setTax(tax);
    		PersonalTax.setTaxMoney(ffMoney);
    		PersonalTax.setPersonName(payeeName);
    		PersonalTax.setProvideDetailId(provideDetailId);
    		personalTaxService.save(PersonalTax);
    	
		return "保存成功";
    	
    }
    
    @PostMapping("/importData")
    public String importData(@RequestParam("excelUploadFile") MultipartFile excelUploadFile){
		return setHistoryService.importData(excelUploadFile);
    	
    }
    
    
    @RequestMapping("/queryByHistory")
    public String queryByHistory(@RequestParam("page") int page,@RequestParam("rows") int rows,@RequestParam("paytaxName") String paytaxName,
    		@RequestParam("starSalesInto") String starSalesInto,@RequestParam("endSalesInto") String endSalesInto,@RequestParam("startaxMoney") String startaxMoney,
    		@RequestParam("endtaxMoney") String endtaxMoney,@RequestParam("starStarTime") String starStarTime,@RequestParam("endStarTime") String endStarTime,
    		@RequestParam("starEndTime") String starEndTime,@RequestParam("endEndTime") String endEndTime,@RequestParam("taxNumber")String taxNumber) {
    	PageInfo<SetHistoryVo> setHistoryVoPageInfo = setHistoryService.queryByHistory(page,rows,paytaxName,starSalesInto,endSalesInto,startaxMoney
    			,endtaxMoney,starStarTime,endStarTime,starEndTime,endEndTime,taxNumber );
    	return JSON.toJSONString(setHistoryVoPageInfo, SerializerFeature.WriteDateUseDateFormat);
    	
    }
    
    
	@RequestMapping("findMoney")
	public List<SellerOrderVo> findMoney(@RequestParam("sellerName") String sellerName,
    		@RequestParam("serviceName") String serviceName,@RequestParam("startDate") String startDate,
            @RequestParam("endDate") String endDate,
            @RequestParam("orderId") String orderId){
		
		return sellerOrderService.findMoney(sellerName, serviceName, startDate, endDate, orderId);
	}
    
    
}
